package module4.homework;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientTest {

    public static void main(String[] args) {
        Socket s1 = null;
        BufferedReader br = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        try {
            //1、提供Socket类型的对象并提供服务器的主机名和端口号
            s1 = new Socket("masai", 8887);
            System.out.println("链接服务器成功!");
            //2、使用输入输出流进行通信
            /*Thread.sleep(10000);*/
            //实现客户端向服务器发送信息的功能
            /*System.out.println("客户端发送数据内容成功！");*/
            br = new BufferedReader(new InputStreamReader(s1.getInputStream()));
            System.out.println(br.readLine());
            oos = new ObjectOutputStream(s1.getOutputStream());
            ois = new ObjectInputStream(s1.getInputStream());
            boolean flag = true;
            while (flag) {
                Scanner sc = new Scanner(System.in);
                String str1 = sc.next();
                String str2 = sc.next();
                //构造user类型的对象，封装变量str1,str2
                UserMessage um = new UserMessage("check", new User(str1, str2));
                oos.writeObject(um);
                //读取回传的对象
                Object obj = ois.readObject();
                //做判断
                if ("success".equals(((UserMessage) obj).getType())) {
                    System.out.println("恭喜登录成功！");
                    flag = false;
                } else {
                    System.out.println("密码或者账户错误，请重新输入：");
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            //3、关闭Socket对象并释放有关的资源
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s1) {
                try {
                    s1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
